package com.tomato.study.jwt.demo;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * jwt demo
 *
 * @author lizhifu
 * @date 2022/4/27
 */
public class JwtDemo {
    public static void main(String[] args) {
        String secret = "123456";

        Date date = new Date(System.currentTimeMillis() + 1000);
        Algorithm algorithm = Algorithm.HMAC256(secret);

        String token =  JWT.create()
                .withClaim("name", "张三")
                .withClaim("age", "18")
                // 设置过期时间
                .withExpiresAt(date)
                // 设置签名算法
                .sign(algorithm);
        System.out.println(token);

        // 校验 token
        JWT.require(Algorithm.HMAC256(secret)).build().verify(token);

        // 获取 token 中的载荷信息
        DecodedJWT jwt = JWT.decode(token);
        String name =  jwt.getClaim("name").asString();
        String age =  jwt.getClaim("age").asString();
        System.out.println(name);
        System.out.println(age);

        // 判断 token 是否过期
        boolean isExpired = jwt.getExpiresAt().before(new Date());
        System.out.println(isExpired);
    }
}
